﻿using System;
using System.Collections.Generic;
using System.Text;
using Runda.EShop.Common.Entity;
using Runda.EShop.Bll.WMSServiceReference;
using Runda.EShop.Common.Utility;

namespace Runda.EShop.Bll.ServiceAdapter
{
    public class WMSServiceAdapter
    {
        private OperateResult PutSOData(BizOrderEntity entity, BizCustomerEntity customer)
        {
            OperateResult result = new OperateResult();
            if (entity == null)
            {
                result.IsSuccess = false;
                result.Message = "未获取到订单";
                return result;
            }

            ERPWSService2Client client = new ERPWSService2Client();
            client.Endpoint.Address = new System.ServiceModel.EndpointAddress(ConfigHelper.ReadConfig("WMSServiceUrl"));

            wmsSecurityInfo wmsSecurityInfo = new wmsSecurityInfo();
            wmsSecurityInfo.username = ConfigHelper.ReadConfig("WMSSoapHeadUserName");
            wmsSecurityInfo.password = ConfigHelper.ReadConfig("WMSSoapHeadPassword");

            wmsParamInfo wmsParam = new wmsParamInfo();
            wmsParam.customerid = "Runda";
            wmsParam.messageid = "106";//不变
            wmsParam.stdno = "SO";
            wmsParam.warehouseid = "7";

            wmsResultInfo wmsResultInfo = new wmsResultInfo();
            wmsSOInfo soInfo = new wmsSOInfo();

            wmsSOHeader[] wmsSOHeaders = new wmsSOHeader[1];
            wmsSOHeaders[0] = new wmsSOHeader();
            wmsSOHeaders[0].SOSTATUS = GetSOStatusByOrderStatus((EnumHelper.OrderStatus)entity.OrderStatus);//正常过来，不管是第一次还是第二次，都是00。订单取消，状态是90。
            wmsSOHeaders[0].SOREFERENCE1 = entity.OrderCode;  
            wmsSOHeaders[0].ORDERTIME = entity.OrderDate.ToString("yyyy-MM-dd hh:mm:ss.fff");
            wmsSOHeaders[0].CUSTOMERID = customer.Enterprise.cCO;
            wmsSOHeaders[0].CONSIGNEEID = customer.Enterprise.cCO.ToUpper() + customer.Enterprise.EntCode.ToUpper();
            //wmsSOHeaders[0].CONSIGNEENAME = customer.CustomerName;
            wmsSOHeaders[0].CONSIGNEENAME = customer.Enterprise.EntName;
            wmsSOHeaders[0].c_CONTACT = entity.ReceiverPhone; 
            wmsSOHeaders[0].c_ADDRESS1 = entity.ReceiveAddr;
            wmsSOHeaders[0].NOTES = entity.Memo;

            wmsSOHeaders[0].h_EDI_02 = entity.OrderStatus.ToString();//由于1被WMS更新掉了，换到2这个字段 130107@gui

            //订单头 接口页签：H_EDI_03 以及H_EDI_04
            //wmsSOHeaders[0].USERDEFINE3 = entity.OrderID.ToString(); //由于1被WMS更新掉了，换到3这个字段
            //wmsSOHeaders[0].USERDEFINE2 = entity.CustomerID.ToString();
            wmsSOHeaders[0].h_EDI_03 = entity.OrderID.ToString();
            wmsSOHeaders[0].h_EDI_04 = entity.CustomerID.ToString(); 

            wmsSODetails[] detailsItem = null;

            if (entity.OrderStatus != (int)EnumHelper.OrderStatus.CustomerConfirm)
            {
                detailsItem = new wmsSODetails[entity.OrderDetails.Count];
                for (int i = 0; i < entity.OrderDetails.Count; i++)
                {
                    detailsItem[i] = new wmsSODetails();
                    detailsItem[i].CUSTOMERID = customer.Enterprise.cCO + customer.Enterprise.EntCode;
                    detailsItem[i].SKU = entity.OrderDetails[i].ProductCode;
                    //detailsItem[i].QTYSHIPPED_EACH = entity.OrderDetails[i].Quantity.ToString();
                    detailsItem[i].QTYORDERED_EACH = entity.OrderDetails[i].Quantity.ToString();
                    detailsItem[i].QTYORDERED = entity.OrderDetails[i].Quantity.ToString();

                    detailsItem[i].LOTATT02 = entity.OrderDetails[i].DueDate.ToString("yyyy-MM-dd");
                    detailsItem[i].LOTATT04 = entity.OrderDetails[i].BatchCode;

                    detailsItem[i].NOTES = entity.OrderDetails[i].Remark.ToEmptyWhenNull();

                    //订单明细 接口页签  D_EDI_01，D_EDI_02，D_EDI_03
                    //detailsItem[i].USERDEFINE1 = entity.OrderDetails[i].OrderID.ToString();
                    //detailsItem[i].USERDEFINE2 = entity.OrderDetails[i].DetailID.ToString();
                    //detailsItem[i].USERDEFINE3 = entity.OrderDetails[i].ProductID.ToString();
                    detailsItem[i].d_EDI_01 = entity.OrderDetails[i].OrderID.ToString();
                    detailsItem[i].d_EDI_02 = entity.OrderDetails[i].DetailID.ToString();
                    detailsItem[i].d_EDI_03 = entity.OrderDetails[i].ProductID.ToString();

                    detailsItem[i].ORDERLINENO = (i + 1).ToString();
                }
            }
            else
            {
                detailsItem = new wmsSODetails[entity.OrderDetailsPatch.Count];
                for (int i = 0; i < entity.OrderDetailsPatch.Count; i++)
                {
                    detailsItem[i] = new wmsSODetails(); 
                    detailsItem[i].CUSTOMERID = customer.Enterprise.cCO + customer.Enterprise.EntCode;
                    detailsItem[i].SKU = entity.OrderDetailsPatch[i].ProductCode;
                    //detailsItem[i].QTYSHIPPED_EACH = entity.OrderDetails[i].Quantity.ToString();
                    detailsItem[i].QTYORDERED_EACH = entity.OrderDetailsPatch[i].ActualQty.ToString();
                    detailsItem[i].QTYORDERED = entity.OrderDetailsPatch[i].ActualQty.ToString();
                    detailsItem[i].LOTATT04 = entity.OrderDetailsPatch[i].BatchCode;
                    detailsItem[i].LOTATT02 = entity.OrderDetailsPatch[i].DueDate.ToString("yyyy-MM-dd");

                    //订单明细 接口页签  D_EDI_01，D_EDI_02，D_EDI_03
                    //detailsItem[i].USERDEFINE1 = entity.OrderDetailsPatch[i].OrderID.ToString();
                    //detailsItem[i].USERDEFINE2 = entity.OrderDetailsPatch[i].DetailID.ToString();
                    //detailsItem[i].USERDEFINE3 = entity.OrderDetailsPatch[i].ProductID.ToString();
                    detailsItem[i].d_EDI_01 = entity.OrderDetailsPatch[i].OrderID.ToString();
                    detailsItem[i].d_EDI_02 = entity.OrderDetailsPatch[i].DetailID.ToString();
                    detailsItem[i].d_EDI_03 = entity.OrderDetailsPatch[i].ProductID.ToString();

                    detailsItem[i].ORDERLINENO = (i + 1).ToString();
                }
            }

            wmsSOHeaders[0].detailsItem = detailsItem;

            soInfo.wmsResultInfo = (wmsResultInfo);
            soInfo.wmsSOHeaders = (wmsSOHeaders);

            wmsResultInfo wmsResult = client.putSOData(wmsSecurityInfo, soInfo, wmsParam);
            if (wmsResult.returnFlag == "0") //失败
            {
                result.IsSuccess = false;
                result.Message = wmsResult.returnDesc;
            }
            else
            {
                result.IsSuccess = true;
                result.Message = "成功";
            }

            return result;
            
        }

        public OperateResult PutSOData(Guid OrderID)
        {
            BizOrderBll bll = new BizOrderBll();
            BizOrderEntity entity = bll.Get<BizOrderEntity>(OrderID);

            //SysOrderServiceStatusEntity orderServiceEntity = bll.Get<SysOrderServiceStatusEntity>(" and OrderID = '"+OrderID+"'");
            //if (orderServiceEntity.Status != 0) {

            //    return new OperateResult();
            //}

            if (entity.OrderStatus == (int)EnumHelper.OrderStatus.CustomerConfirm)
            {
                List<BizOrderDetailPatchEntity> detailsPatch = bll.GetAll<BizOrderDetailPatchEntity>(" and OrderID='" + OrderID + "'");
                entity.OrderDetailsPatch = detailsPatch.FindAll(delegate(BizOrderDetailPatchEntity ent) { return ent.ActualQty != 0; }); //数量为0不能下定，过滤
            }
            else
            {
                List<BizOrderDetailEntity> details = bll.GetAll<BizOrderDetailEntity>(" and OrderID='" + OrderID + "'");
                entity.OrderDetails = details.FindAll(delegate(BizOrderDetailEntity ent) { return ent.Quantity != 0; }); //数量为0不能下定，过滤
            }

            BizCustomerEntity customer = bll.Get<BizCustomerEntity>(entity.CustomerID);

            BizEnterpriseEntity entEntity = bll.Get<BizEnterpriseEntity>(" and EntID in (select EntID from Biz_Customer where CustomerID='"+entity.CustomerID+"')");
            customer.Enterprise = entEntity;

            return this.PutSOData(entity, customer);
        }

        public OperateResult Test()
        {
            OperateResult result = new OperateResult();

            ERPWSService2Client client = new ERPWSService2Client();

            wmsSecurityInfo wmsSecurityInfo = new wmsSecurityInfo();
            wmsSecurityInfo.username = "flux22";
            wmsSecurityInfo.password = "40222";

            wmsParamInfo wmsParam = new wmsParamInfo();
            wmsParam.customerid = "Runda";
            wmsParam.messageid = "106";//不变
            wmsParam.stdno = "SO";
            wmsParam.warehouseid = "7";

            wmsResultInfo wmsResultInfo = new wmsResultInfo();
            wmsSOInfo soInfo = new wmsSOInfo();

            wmsSOHeader[] wmsSOHeaders = new wmsSOHeader[1];
            wmsSOHeaders[0] = new wmsSOHeader();
            wmsSOHeaders[0].ORDERNO = ("201211200001");
            wmsSOHeaders[0].ORDERTYPE = ("1");
            //wmsSOHeaders[0].setSOSTATUS("00");
            //wmsSOHeaders[0].setORDERTIME("1900-01-01");
            wmsSOHeaders[0].CUSTOMERID = ("777");
            //wmsSOHeaders[0].setSOREFERENCE1("1111111");
            //wmsSOHeaders[0].setSOREFERENCE2("2222222");
            //wmsSOHeaders[0].setRELEASESTATUS("N");
            wmsSOHeaders[0].CONSIGNEEID = ("777zzjyyl");
            //wmsSOHeaders[0].setCONSIGNEENAME("上海西域");
            //wmsSOHeaders[0].setC_ADDRESS1("上海航津路");
            //wmsSOHeaders[0].setC_ADDRESS2("上海");
            //wmsSOHeaders[0].setC_CITY("上海");
            //wmsSOHeaders[0].setC_PROVINCE("上海");
            //wmsSOHeaders[0].setC_COUNTRY("上海");
            //wmsSOHeaders[0].setC_ZIP("410000");
            //wmsSOHeaders[0].setC_CONTACT("李天佑");
            //wmsSOHeaders[0].setC_MAIL("lity@flux.com.cn");
            //wmsSOHeaders[0].setC_FAX("lity@flux.com.cn");
            //wmsSOHeaders[0].setC_TEL1("111111");
            //wmsSOHeaders[0].setC_TEL2("222222");
            //wmsSOHeaders[0].setUSERDEFINE6("Y");
            //wmsSOHeaders[0].setCARRIERID("XYJD");

            wmsSODetails[] detailsItem = new wmsSODetails[1];
            detailsItem[0] = new wmsSODetails();
            detailsItem[0].ORDERNO = ("201211200001");
            //detailsItem[0].ORDERLINENO = ("1");
            detailsItem[0].CUSTOMERID = ("777zzjyyl");
            detailsItem[0].SKU = "223785"; //ProductCode
            //detailsItem[0].setSKU("0021002");
            detailsItem[0].QTYSHIPPED_EACH = "10";
            //detailsItem[0].QTYORDERED_EACH("11.0");
            wmsSOHeaders[0].detailsItem = detailsItem;


            soInfo.wmsResultInfo = (wmsResultInfo);
            soInfo.wmsSOHeaders = (wmsSOHeaders);


            wmsResultInfo wmsResult = client.putSOData(wmsSecurityInfo, soInfo, wmsParam);

            if (wmsResult.returnFlag == "0") //失败
            {
                result.IsSuccess = false;
                result.Message = wmsResult.returnDesc;
                return result;
            }

            return result;
        }

        /// <summary>
        ///  WMS订单状态
        /// </summary>
        /// <param name="status"></param>
        /// <remarks>
        /// №1Xuxl 14:40:41  有一个状态吧 №1Xuxl 14:40:44 好像是 90  №1Xuxl 14:41:08 正常订单过来的时候，状态是啥 №1Xuxl 14:41:18 订单取消是90 №1Xuxl 14:41:27 正常过来应该是 00 
        ///</remarks>
        /// <returns></returns>
        private string GetSOStatusByOrderStatus(EnumHelper.OrderStatus status)
        {
            string SOStatus = "";
            switch (status)
            { 
                case EnumHelper.OrderStatus.Cancel:
                    SOStatus = "90";
                    break;
                default:
                    SOStatus = "00";
                    break;
            }
            return SOStatus;
        }
    }
}
